package com.platform.controller.tenant;

import com.platform.common.annotation.Log;
import com.platform.common.constant.Constants;
import com.platform.common.core.controller.BaseController;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.core.domain.entity.SysRole;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.page.TableDataInfo;
import com.platform.common.enums.BusinessType;
import com.platform.common.utils.SecurityUtils;
import com.platform.common.utils.StringUtils;
import com.platform.system.service.ISysTenantRoleService;
import com.platform.system.service.ISysTenantUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Huangkai
 */
@RestController
@RequestMapping("/tenant/user")
public class UserTenantController extends BaseController {

    @Autowired
    private ISysTenantUserService iSysTenantUserService;

    @Autowired
    private ISysTenantRoleService sysTenantRoleService;
    /**
     * 新增租户
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:add')")
    @Log(title = "新增租户", businessType = BusinessType.INSERT)
    @PostMapping("/addTenantUser")
    public AjaxResult addTenantUser(@Validated @RequestBody SysUser user) {
        if (!iSysTenantUserService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !iSysTenantUserService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !iSysTenantUserService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserType("01");
        user.setNickName(StringUtils.getRandomName(Constants.NUM_SIX));
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setStatus(Constants.STR_TWO);
        return toAjax(iSysTenantUserService.insertTenantUser(user));
    }
    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {

        logger.info("测试{}", userId);
        AjaxResult ajax = AjaxResult.success();
        SysUser user = iSysTenantUserService.selectUserById(userId);
        List<SysRole> roles = sysTenantRoleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }
    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        iSysTenantUserService.checkUserDataScope(userId);
        iSysTenantUserService.insertUserAuth(userId, roleIds);
        return success();
    }
    /**
     * 获取租户列表
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        user.setUserType("01");
        List<SysUser> list = iSysTenantUserService.selectTenantUserList(user);
        return getDataTable(list);
    }

    /**
     * 查询租户详情
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult list(@PathVariable(value = "userId", required = false) Long userId) {
        SysUser sysUser = iSysTenantUserService.selectUserById(userId);
        return AjaxResult.success(sysUser);
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:remove')")
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return iSysTenantUserService.deleteTenantUserByIds(userIds);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        iSysTenantUserService.checkUserAllowed(user);
        iSysTenantUserService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(iSysTenantUserService.updateUser(user));
    }
    /**
     * 修改租户状态
     */
    @PreAuthorize("@ss.hasPermi('tenant:tenantUser:updateTenantUserStatus')")
    @Log(title = "修改租户状态", businessType = BusinessType.UPDATE)
    @PutMapping("/updateTenantUserStatus")
    public AjaxResult updateTenantUserStatus(@Validated @RequestBody SysUser user) {
        logger.info("传古来的值{}", user);
        user.setUpdateBy(getUsername());
        return toAjax(iSysTenantUserService.updateUser(user));
    }
}
